﻿@using Compass.Wasm.Shared.Files
@inject HttpClient Http
@if (string.IsNullOrEmpty(result))
{
    <span style="font-weight:bold;">@Title ：</span>
    <br />
    if (imageUrls.Count!=0)
    {
        <Row ItemsPerRow="ItemsPerRow.Three">
            @foreach (var imageUrl in imageUrls)
            {
                <ImageWithDelete ImageUrl="@imageUrl" DeleteImage="DeleteImage"></ImageWithDelete>
            }
        </Row>
    }
}
else
{
    <span>@result</span>
}
<InputFile class="form-control mb-2" OnChange="OnInputImageChange" accept="image/*" />
@code {
    [Parameter]
    public string Title { get; set; }

    [Parameter]
    public string MultiImageUrl { get; set; }
    [Parameter]
    public EventCallback<string> MultiImageUrlChanged { get; set; }
    //自定义组件实现双向绑定，https://blog.csdn.net/playermaker57/article/details/105443467

    public string result = string.Empty;
    List<string> imageUrls = new();

    Task DeleteImage(string imageUrl)
    {
        imageUrls.Remove(imageUrl);
        return RefreshMultiImageUrl();
    }

    protected override void OnInitialized()
    {
        if (!string.IsNullOrWhiteSpace(MultiImageUrl)) imageUrls = MultiImageUrl.Split('\n').ToList();
    }
    private async Task OnInputImageChange(InputFileChangeEventArgs e)
    {
        var file = e.File;//一个文件
        using var content = new MultipartFormDataContent();
        content.Add(content: new StreamContent(file.OpenReadStream(1024 * 1024*100)),
            name: "\"files\"", fileName: file.Name);
        try
        {
            var response = await Http.PostAsync("api/Uploader", content);
            var uploadResponse = await response.Content
                .ReadFromJsonAsync<UploadResponse>();
            //如果重复就不要继续添加了
            if (!imageUrls.Contains(uploadResponse.RemoteUrl.ToString()))
            {
                imageUrls.Add(uploadResponse.RemoteUrl.ToString());
                await RefreshMultiImageUrl();
            }
        }
        catch (Exception ex)
        {
            result =$"上传图片异常：{ex}";
        }
    }
    //更新MultiImageUrl，以实现双向绑定
    Task RefreshMultiImageUrl()
    {
        MultiImageUrl = string.Join('\n', imageUrls);
        //双向绑定
        return MultiImageUrlChanged.InvokeAsync(MultiImageUrl);
    }
}
